package org.hj.modules.act.actmodel.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hj.common.api.vo.Result;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.vo.LoginUser;
import org.hj.modules.AcBaseController;
import org.hj.modules.act.actmodel.service.ActModelService;
import org.hj.modules.util.PageData;
import org.hj.modules.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 模型管理
 * @author gbw
 * 2020/5/26
 */
@Slf4j
@RestController
@RequestMapping("/act/actmodel")
public class ActModelController  extends AcBaseController {

    @Autowired
    private ActModelService actModelService;
    @Autowired
    private RepositoryService repositoryService;


    /**列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/list")
    @ResponseBody
    public Result<IPage> list(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) throws Exception{

        Result<IPage> result = new Result<>();

        /*ModelQuery modelQuery = repositoryService.createModelQuery()
                //.modelTenantId(String.valueOf(TenantContextHolder.getTenantId()))
                .latestVersion().orderByLastUpdateTime().desc();
        String category = req.getParameter("category");
        if (StrUtil.isNotBlank(category)) {
            modelQuery.modelCategory(category);
        }

        IPage page = new Page(pageNo, pageSize);
        page.setTotal(modelQuery.count());
        page.setRecords(modelQuery.listPage((pageNo - 1) * pageSize, pageSize));
        result.setResult(page);
        return result;*/
        IPage page =new Page(pageNo, pageSize);
        String category=req.getParameter("category");
        List<PageData> dataList = actModelService.getpage(category,pageNo,pageSize);
        int count =actModelService.getTotal(category);
        page.setRecords(dataList);
        page.setTotal(count);
        result.setResult(page);
        return result;



    }



    /**保存
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/add")
    public Object add(HttpServletRequest req) throws Exception{

        Map<String,Object> map = new HashMap<String,Object>();
        String info = "添加成功 ！";
        String process_author = req.getParameter("process_author");	//流程作者
        String name  = req.getParameter("name");					//流程名称
        String process_id  = req.getParameter("process_id");		//流程标识
        String modelname  = req.getParameter("modelname");			//模型名称
        String description  = req.getParameter("description");		//模型描述
        String category  = req.getParameter("category");			//模型分类
        String modelId = createModel(process_id,process_author,name,modelname,description,category);
        map.put("success",true);//返回结果
        map.put("message",info);//返回结果
        return map;
    }

    /**去修改类型页面获取数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/goEdit")
    public Object goEdit(HttpServletRequest req)throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";
        Map<Object, Object> pd=actModelService.findById(req.getParameter("ID_"));	//根据ID读取
        map.put("pd", pd);
        map.put("result", result);
        return map;
    }

    /**修改类型
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/edit")
    public Object edit(HttpServletRequest req) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";
        String category= req.getParameter("category");
        String id =req.getParameter("ID_");
        actModelService.edit(category,id);
        map.put("result", result);
        return map;
    }


    /**删除
     * @param req
     * @throws Exception
     */
    @RequestMapping(value="/delete")
    public Object delete(HttpServletRequest req) throws Exception{
        Map<String,String> map = new HashMap<>();

        deleteModel(req.getParameter("ID_"));
        map.put("result", "success");				//返回结果
        return map;
    }


    /**批量删除
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/deleteAll")
    public Object deleteAll(HttpServletRequest req) throws Exception{
        Map<String,Object> map = new HashMap<>();
        String errInfo = "success";

        String DATA_IDS = req.getParameter("DATA_IDS");
        if(Tools.notEmpty(DATA_IDS)){
            String ArrayDATA_IDS[] = DATA_IDS.split(",");
            for(int i=0;i<ArrayDATA_IDS.length;i++){
                deleteModel(ArrayDATA_IDS[i]);
            }
        }else{
            errInfo = "error";
        }
        map.put("result", errInfo);				//返回结果
        return map;
    }

    /**获取当前用户
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getAuthor")
    public Object getAuthor()throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String errInfo = "success";
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        map.put("process_author", sysUser.getRealname());	//流程作者
        map.put("result", errInfo);							//返回结果
        return map;
    }

    /**部署流程定义
     * @return
     */
    @RequestMapping(value="/deployment")
    public Object deployment(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";
        try{
            deploymentProcessDefinitionFromModelId( req.getParameter("modelId"));//部署流程定义
        }catch (Exception e){
            result = "error";
        }finally{
            map.put("result", result);
        }
        return map;
    }


    /**判断能否正常根据模型ID导出xml文件
     * @return
     */
    @RequestMapping(value="/isCanexportXml")
    public Object isCanexportXml(HttpServletRequest req,HttpServletResponse response){
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";

        try{
            isCanexportXmlFromModelId(response,req.getParameter("modelId"));
        }catch (Exception e){
            result = "error";
        }finally{
            map.put("result", result);
        }
        return map;
    }

    /**获取预览XML页面code
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getXmlView")
    public Object getXmlView(HttpServletRequest req,HttpServletResponse response)throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";

        String code = viewXmlFromModelId(req.getParameter("modelId"));
        map.put("code", code);
        map.put("result", result);
        return map;
    }
    /**正式根据模型ID导出xml文件
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/exportXml")
    public void exportXml(HttpServletRequest req,HttpServletResponse response) throws Exception{

        exportXmlFromModelId(response,req.getParameter("modelId"));	//导出xml文件
    }

    /**从流程定义映射模型
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/saveModelFromPro")
    public Object saveModelFromPro(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String,Object>();
        String result = "success";

        String processDefinitionId = req.getParameter("processDefinitionId"); 		//流程定义ID
        try {
            saveModelFromPro(processDefinitionId);
        } catch (Exception e) {
            result = "errer";
        }
        map.put("result", result);
        return map;
    }

}
